<template>
  <div v-if="showGetLink || showGetDown" class="linkBuySection">
    <small v-show="!isNull(ErrorsMxg)" class="errorMxg">{{ ErrorsMxg }}</small><br>
    <h3 class="linkBuyCoinBalance">您当前拥有的硬币(积分): {{ coin }}</h3>
    <h3 class="linkBuyCostTitle">您获取本资源下载连接的需要花费的积分如下:</h3>
    <p class="linkBuyCoinHint">说明:本站硬币(积分)唯一获取方式:每日首次访问并登录本站即可获取1硬币</p>
    <h4 class="linkBuyExternalItem" v-if="showGetLink">
      外部连接: {{ Resource.resourceExtensionInformation.linkPrice }} 硬币
      (您当前的硬币: {{ isCoinEnoughForLink ? '充足,可以获取此选项' : '不足以获取此选项' }})
    </h4>
    <hr>
    <h4 class="linkBuyLocalItem" v-if="showGetDown">
      服务器下载连接: {{ Resource.resourceExtensionInformation.downloadLocallyPrice }} 硬币(积分)
      ,当前服务器中
      {{ Resource.resourceExtensionInformation.hasDownloadLocally === 'yes' ? '存在' : '不存在' }}本地文件
      ,您当前的硬币: {{ isCoinEnoughForDownload ? '充足,可以购买此选项' : '不足以获取此选项' }}
    </h4>

    <div class="linkBuyBtnContainer">
      <p class="linkBuyValidityHint">请注意:链接购买后有效期为24小时,请尽快获取并使用!</p>
      <button @click="buyLink(true,false)" :disabled="!isCoinEnoughForLink" class="linkBuyExternalBtn"
              v-if="showGetLink">购买外部连接
      </button>
      <button @click="buyLink(false,true)" :disabled="!isCoinEnoughForDownload " class="linkBuyLocalBtn"
              v-if="showGetDown">购买本地下载
      </button>
      <button @click="buyLink(true,true)" :disabled=" !(isCoinEnoughForDownload && isCoinEnoughForLink)"
              class="linkBuyAllBtn">
        我全部都要(all-in)
      </button>
    </div>
  </div>

  <div v-if="!needGetLink" class="linkGetSection">
    <button @click="getLink" v-if="canGetLink" class="linkGetBtn">点击获取链接</button>
    <label v-if="canGetLink" class="linkGetAllLabel">获取所有信息(包括失效的链接信息):
      <input type="checkbox" v-model="isAll"/>
    </label>
    <button @click="getDownloadLink" v-if="canGetDownloadLink" class="linkGetDownloadBtn">点击获取下载链接</button>
  </div>
  <div v-if="hasLink" class="linkListContainer">
    <Link :LinkList="linkList" :hasLink="linkList.length > 0" :isDown="hasDownLink" :rId="Resource.rId"/>
  </div>
</template>

<script setup lang="ts">
import {computed, onMounted, ref} from "vue"
import {globalConst} from "@constants/globalConst.js"
import axiosInstance from "@utils/axiosInstance.ts"
import {getUser, getUserToken, setUser} from "@stores/localStorage.js"
import {getToken} from "@stores/tokenStorage.ts"
import ResponseResult from "@models/ReturnResult.js"
import {isNull} from "@utils/stringUtil.js"
import Link from "@components/link.vue"

// ---------------- props 类型化 ----------------
interface ResourceExtension {
  linkPrice: number
  downloadLocallyPrice: number
  hasDownloadLocally: string
}

interface ResourceType {
  rId: number
  resourceId: number
  resourceExtensionInformation: ResourceExtension
}

const props = defineProps<{ Resource: ResourceType }>()
const Resource = props.Resource
const uid = getUser().userId
// ---------------- ref 定义 ----------------
const coin = ref(getUser()?.coin ?? 0)
const canGetLink = ref(false)
const canGetDownloadLink = ref(false)
const isAll = ref(false)
const needGetLink = ref(true)
const ErrorsMxg = ref('')
const linkList = ref<Array<any>>([])
const hasLink = ref(false)
const hasDownLink = ref(false)
const showGetLink = ref(true)
const showGetDown = ref(true)
// ---------------- 计算属性 ----------------
const isCoinEnoughForLink = computed(() => coin.value >= Number(Resource.resourceExtensionInformation.linkPrice || 0))
const isCoinEnoughForDownload = computed(() => coin.value >= Number(Resource.resourceExtensionInformation.downloadLocallyPrice || 0))

// ---------------- LinkAndDownload 类 ----------------
class LinkAndDownload {
  resourceId: number
  isLinks: boolean
  isDownload: boolean

  constructor(data: any) {
    this.resourceId = data.resourceId || -1
    this.isLinks = data.links
    this.isDownload = data.download
  }
}

// ---------------- 初始化检查 ----------------
onMounted(async () => {
  try {
    const res = await axiosInstance.get(`${globalConst.baseUrl}user/testHasLink/${Resource.rId}`, {
      headers: {
        [globalConst.tokenName]: getUserToken(),
      }
    })
    const response = ResponseResult.fromApiResponse(res.data)
    needGetLink.value = !response.isSuccess()
    if (response.isSuccess()) {
      const i = new LinkAndDownload(response.returnResult)
      if (i.resourceId === Resource.rId) {
        canGetLink.value = i.isLinks
        canGetDownloadLink.value = i.isDownload
        showGetLink.value = !i.isLinks
        showGetDown.value = !i.isDownload
      }
    }
  } catch (err) {
    console.error(err)
    ErrorsMxg.value = '初始化失败'
  }
})

// ---------------- 购买链接 ----------------
async function buyLink(isLinks: boolean, isDownload: boolean) {
  if (!Resource) {
    alert("错误!!不存在的资源信息!")
    return
  }
  try {
    const response = await axiosInstance.post(`${globalConst.baseUrl}user/buyLink`, {
      resourceId: Resource.rId,
      isLinks,
      isDownload,
    }, {
      headers: {
        [globalConst.tokenName]: getUserToken(),
        [globalConst.userBuyToken]: getToken(globalConst.userBuyToken + "r" + Resource.rId + "u" + uid),
      }
    })
    const result = ResponseResult.fromApiResponse(response.data)
    if (result.isSuccess()) {
      alert(result.msg)
      coin.value = getUser()?.coin ?? coin.value
    } else {
      ErrorsMxg.value = result.msg as string
    }
  } catch (err) {
    console.error(err)
    ErrorsMxg.value = '购买请求失败'
  }
}

// ---------------- 获取外部链接 ----------------
async function getLink() {
  try {
    const response = await axiosInstance.get(`${globalConst.baseUrl}user/getLinks?isAll=${isAll.value}&rId=${Resource.rId}`, {
      headers: {
        [globalConst.tokenName]: getUserToken(),
      }
    })
    const result = ResponseResult.fromApiResponse<Array<any>>(response.data)
    if (result.isSuccess() && !isNull(result.returnResults) && result.returnResults.length > 0) {
      linkList.value = result.returnResults
      coin.value = getUser().coin
      setUser(getUser())
      needGetLink.value = false
      hasDownLink.value = false
      hasLink.value = true
      canGetLink.value = false
      canGetDownloadLink.value = false
      showGetLink.value = false
      alert(result.msg)
    } else {
      alert("购买出错了,因为:" + result.msg)
    }
  } catch (err) {
    console.error(err)
    alert("获取链接失败")
  }
}

// ---------------- 获取本地下载 ----------------
async function getDownloadLink() {
  try {
    const response = await axiosInstance.get(`${globalConst.baseUrl}user/getDown/${Resource.rId}`, {
      headers: {
        [globalConst.tokenName]: getUserToken(),
      }
    })
    const result = ResponseResult.fromApiResponse<Array<string>>(response.data)
    if (result.isSuccess() && !isNull(result.returnResults) && result.returnResults.length > 0) {
      linkList.value = result.returnResults
      hasDownLink.value = true
      canGetLink.value = false
      canGetDownloadLink.value = false
      hasLink.value = true
      needGetLink.value = false
      showGetDown.value = false
      alert(result.msg + ",如果您没看到链接获取按钮请手动刷新一下页面")
    } else {
      alert("购买出错了,因为:" + result.msg)
    }
  } catch (err) {
    console.error(err)
    alert("获取下载链接失败")
  }
}
</script>
<style scoped>
/* ======== 主体容器 ======== */
.linkBuySection,
.linkGetSection,
.linkListContainer {
  width: 85%;
  margin: 2em auto;
  padding: 1.5em 2em;
  border-radius: 12px;
  background: rgba(40, 0, 0, 0.35); /* 可调整容器透明度 */
  backdrop-filter: blur(6px); /* 可调整模糊程度 */
  box-shadow: 0 0 12px rgba(255, 80, 100, 0.25);
  color: #f8f8f8;
  transition: all 0.3s ease;
}

.linkBuySection:hover,
.linkGetSection:hover {
  background: rgba(60, 0, 0, 0.4);
  transform: translateY(-2px);
}

/* ======== 提示与错误 ======== */
.errorMxg {
  display: block;
  color: #ff4d4d;
  font-weight: bold;
  margin-bottom: 0.8em;
}

.linkBuyCoinHint,
.linkBuyValidityHint {
  font-size: 0.9em;
  color: #d0d0d0;
  margin-top: 0.5em;
}

.linkBuyCoinBalance {
  color: #ffd9df;
  font-size: 1.2em;
  margin-bottom: 0.6em;
}

.linkBuyCostTitle {
  color: #ffc8c8;
  font-size: 1.1em;
  margin-bottom: 0.5em;
}

.linkBuyExternalItem,
.linkBuyLocalItem {
  font-size: 1em;
  margin: 0.8em 0;
  color: #ffffff;
}

/* ======== 按钮组 ======== */
.linkBuyBtnContainer {
  display: flex;
  flex-wrap: wrap;
  gap: 1em;
  margin-top: 1.5em;
  align-items: center;
}

.linkBuyExternalBtn,
.linkBuyLocalBtn,
.linkBuyAllBtn,
.linkGetBtn,
.linkGetDownloadBtn {
  border: none;
  border-radius: 8px;
  padding: 0.7em 1.2em;
  font-size: 1em;
  font-weight: bold;
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
}

/* 单独设置渐变色差异 */
.linkBuyExternalBtn {
  background: linear-gradient(145deg, rgba(255, 90, 110, 0.85), rgba(180, 0, 0, 0.8));
}

.linkBuyLocalBtn {
  background: linear-gradient(145deg, rgba(255, 110, 130, 0.85), rgba(200, 20, 20, 0.8));
}

.linkBuyAllBtn {
  background: linear-gradient(145deg, rgba(255, 150, 160, 0.9), rgba(220, 40, 40, 0.9));
}

/* 获取按钮组 */
.linkGetBtn,
.linkGetDownloadBtn {
  background: linear-gradient(145deg, rgba(255, 90, 110, 0.9), rgba(160, 0, 0, 0.9));
  margin-top: 1em;
}

.linkBuyExternalBtn:hover,
.linkBuyLocalBtn:hover,
.linkBuyAllBtn:hover,
.linkGetBtn:hover,
.linkGetDownloadBtn:hover {
  filter: brightness(1.15);
  transform: scale(1.03);
}

.linkBuyExternalBtn:disabled,
.linkBuyLocalBtn:disabled,
.linkBuyAllBtn:disabled {
  background: rgba(100, 0, 0, 0.5);
  color: #aaa;
  cursor: not-allowed;
}

/* ======== 复选框优化 ======== */
.linkGetAllLabel {
  display: flex;
  align-items: center;
  gap: 0.6em;
  margin-top: 0.5em;
  font-size: 0.95em;
  color: #ffc8c8;
}

.linkGetAllLabel input[type="checkbox"] {
  width: 18px; /* 调整大小 */
  height: 18px;
  border-radius: 4px;
  border: 2px solid #ff5a6e;
  background: rgba(0, 0, 0, 0.3);
  accent-color: #ff5a6e; /* Firefox & 支持的浏览器 */
  cursor: pointer;
  transition: all 0.2s ease;
}

.linkGetAllLabel input[type="checkbox"]:hover {
  filter: brightness(1.2);
}

/* ======== 链接列表容器 ======== */
.linkListContainer {
  margin-top: 2em;
  border: 1px solid rgba(255, 80, 100, 0.2);
  padding: 1.2em;
  border-radius: 10px;
}


</style>
